/**
* 图片上传
*/ 
<template>
  <div>
    <el-upload
    ref="upload"
      :action="mAction"
      list-type="picture-card"
      multiple
      :limit="imgLimit"
      :file-list="fileList"
      :class="{ hide: hideUpload }"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-exceed="handleExceed"
      :on-error="imgUploadError"
      :on-change="changeImg"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import $ from "jquery";
export default {
  name: "upload",
  //子组件访问父组件数据的唯一接口
  props: {
    mAction: { type: String }, //action请求 
    imgLimit: { type: Number, default: 1 }, //设置上传数量
    fileSize: { type: Number, default: 10 }, //设置图片大小
    fileListStr: "", //查看已上传图片
    isShowUpload: { type: Boolean, default: false }, //是否显示上传操作
  },
  data() {
    return {
      aliyunOssToken: {}, //web直传参数
      hideUpload: false,
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      uploadNum:0,// 已上传的数量
      noNum:0,//未上传的数量
    };
  },
  // 注册组件
  components: {
  },
  // 创建完毕状态(里面是操作)
  created() {
   if(this.fileListStr){
      this.uploadNum=this.fileListStr.length;
    }else{
      this.uploadNum=0;
    }
    this.fileList = this.imageConversion(this.imgLimit, this.fileListStr);
    this.hideUpload = this.fileList.length >= this.imgLimit;
    this.getupload();
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取上传阿里云服务器需要的参数
    getupload() {
      // this.aliyunOssToken = this.ADDRESSLIST.aliyunOssToken;
    },
    //自定义上传行为
    handleRequest(row) {
      //上传阿里云服务器
      var fileName = row.file.uid;
      var formData = new FormData();
      //注意formData里append添加的键的大小写
      formData.append("key", this.aliyunOssToken.dir + fileName); //存储在oss的文件路径
      // formData.append("key", _self.aliyunOssToken.dir); //存储在oss的文件路径
      formData.append("OSSAccessKeyId", this.aliyunOssToken.accessid); //accessKeyId
      formData.append("policy", this.aliyunOssToken.policy); //policy
      formData.append("Signature", this.aliyunOssToken.signature); //签名
      //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
      // formData.append("file", params.file);
      formData.append("file", row.file);
      formData.append("success_action_status", 200); //成功后返回的操作码
      // var tex=_self.aliyunOssToken.host.substr(1,_self.aliyunOssToken.host.length-1)
      var url = this.aliyunOssToken.host;
      var fileUrl =
        this.aliyunOssToken.host + "/" + this.aliyunOssToken.dir + fileName;
      var _this = this;
      $.ajax({
        url: url,
        type: "POST",
        data: formData,
        // async: false,
        cache: false,
        contentType: false,
        withCredentials: true,
        processData: false,
        success: function (data) {
          //   this.hideUpload = fileList.length >= this.imgLimit;
          console.log(fileUrl);
        },
        error: function (data) {
          this.$message.error("上传失败");
        },
      });
    },
    //   图片上传监听事件
    changeImg(file, fileList) {
      this.hideUpload = fileList.length >= this.imgLimit;
    },
    //   文件列表移除文件时
    handleRemove(file, fileList) {
      //移除图片
      var arr = this.fileList;
      arr.forEach((item, index) => {
        if (item.url == file.url) {
          arr.splice(index, 1);
        }
      });
      this.fileList = arr;

      this.$emit("getImgList", this.fileList);
      this.hideUpload = fileList.length >= this.imgLimit;
    },
    // 点击文件列表中已上传的文件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //文件上传之前调用做一些拦截限制
    beforeAvatarUpload(file) {
      const isJPG = true;
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < this.fileSize;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 " + this.fileSize + "MB!");
      }
      return isJPG && isLt2M;
    },
    //上传成功
    handleAvatarSuccess(res, file, fileList) {
      //图片上传成功
      var that=this;
      that.noNum+=1;
      if(that.noNum == (fileList.length-that.uploadNum)){
        that.fileList=fileList;
        that.$emit("getImgList", that.fileList);
        that.noNum=0;
      }
    },
    /**
     * 处理获取服务地址转成本地查看
     * type:图片数量
     * parameter:图片参数
     */
    imageConversion: function (type, parameter) {
      let imgList = [];
      if (type > 1) {
        if (parameter) {
          for (let i = 0; i < parameter.length; i++) {
            let img = {
              url: parameter[i],
              response: "",
            };
            imgList.push(img);
          }
        }
        return imgList;
      } else {
        if (parameter) {
          let img = {
            url: parameter,
            response: "",
          };
          imgList.push(img);
        }

        return imgList;
      }
    },
    handleExceed(files, fileList) {
      //图片上传超过数量限制
      this.$message.error("上传图片不能超过" + this.imgLimit + "张!");
      this.fileList = fileList;
      this.$emit("getImgList", this.fileList);
    },
    imgUploadError(err, file, fileList) {
      //图片上传失败调用
      this.$message.error("上传图片失败!");
      this.$emit("getImgList", fileList);
      this.hideUpload = fileList.length >= this.imgLimit;
    },
  },
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>